from fastapi import APIRouter, File, UploadFile, HTTPException
import os
import shutil
from uuid import uuid4
from datetime import datetime
from typing import Optional

router = APIRouter()

# 上传目录
UPLOAD_DIR = "backend/uploads"
# 确保上传目录存在
os.makedirs(UPLOAD_DIR, exist_ok=True)

@router.post("/")
async def upload_file(file: UploadFile = File(...)):
    """
    上传文件API
    """
    try:
        # 生成唯一文件名
        file_extension = os.path.splitext(file.filename)[1]
        unique_filename = f"{uuid4().hex}{file_extension}"
        
        # 按年月日创建子目录
        today = datetime.now().strftime("%Y/%m/%d")
        upload_dir = os.path.join(UPLOAD_DIR, today)
        os.makedirs(upload_dir, exist_ok=True)
        
        # 文件保存路径
        file_path = os.path.join(upload_dir, unique_filename)
        
        # 保存文件
        with open(file_path, "wb") as buffer:
            shutil.copyfileobj(file.file, buffer)
        
        # 返回文件URL
        relative_path = os.path.join(today, unique_filename).replace("\\", "/")
        url = f"/uploads/{relative_path}"
        
        return {"url": url, "filename": unique_filename}
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"上传文件失败: {str(e)}") 